/*
 * Copyright (C) 2009 aileron.cc
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cc.aileron.twitter.mail;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Message;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;

import cc.aileron.commons.resource.ResourceNotFoundException;
import cc.aileron.commons.util.ResourceUtils;
import cc.aileron.mail.MailetApplication;
import cc.aileron.mail.MailetMain;

/**
 * @author Aileron
 */
public class TwitterMail implements MailetApplication
{
    /**
     * @param args
     * @throws Exception
     */
    public static void main(final String... args) throws Exception
    {
        MailetMain.main(TwitterMail.class);
    }

    @Override
    public void execute(final Message message) throws Exception
    {
        final String content = message.getContent()
            .toString()
            .substring(0, 140);
        post(content);
    }

    /**
     * @param status
     * @throws Exception
     */
    public void post(final String status) throws Exception
    {
        final HttpClient client = new HttpClient();
        client.getState()
            .setCredentials(
                    new AuthScope("twitter.com", 443, AuthScope.ANY_REALM),
                    new UsernamePasswordCredentials(user, password));

        final PostMethod method = new PostMethod(
                "https://twitter.com/statuses/update.json");
        method.addParameter("status", status);
        method.setDoAuthentication(true);
        client.executeMethod(method);
    }

    /**
     * @throws ResourceNotFoundException
     * @throws IOException
     * 
     */
    public TwitterMail() throws IOException,
            ResourceNotFoundException
    {
        final Properties properties = ResourceUtils.resource(
                "twitter.properties")
            .toProperties();
        user = properties.getProperty("user");
        password = properties.getProperty("password");
    }

    private final String password;
    private final String user;
}
